#include "StdAfx.h"
#include "A2DDevice.h"

A2DDevice::A2DDevice(void)
{

}

A2DDevice::~A2DDevice(void)
{
}

bool A2DDevice::Create( HWND window, bool windowed, CSize size, UINT refreshRate )
{
	if (!IsWindow(window))
		return false;

	if (size.cx <= 0 || size.cy <= 0)
	{
		if (windowed)
		{
			CRect windowRect;
			if (!GetClientRect(window, windowRect))
				return false;
			size = windowRect.Size();
		}
		else
			return false;
	}
	else if (window) 
	{
		CRect windowRect(CPoint(0, 0), size);
		DWORD windowStyle = GetWindowLongW(window, GWL_STYLE);
		BOOL windowHasMenu = (GetMenu(window) != nullptr);
		DWORD windowExStyle = GetWindowLongW(window, GWL_EXSTYLE);
		if (!AdjustWindowRectEx(windowRect, windowStyle, windowHasMenu, windowExStyle))
			return false;
		SetWindowPos(window, nullptr, 0, 0, windowRect.Width(), windowRect.Height(), SWP_NOMOVE | SWP_NOZORDER);
	}
	
	CComPtr<IDirect3D9> d3d = Direct3DCreate9(D3D_SDK_VERSION);
	if (d3d == nullptr)
		return false;

	D3DPRESENT_PARAMETERS d3dParams;
	ZeroMemory(&d3dParams, sizeof(d3dParams));
	d3dParams.BackBufferWidth = size.cx;
	d3dParams.BackBufferHeight = size.cy;
	d3dParams.BackBufferFormat = D3DFMT_X8R8G8B8;
	d3dParams.BackBufferCount = 1;
	d3dParams.MultiSampleType = D3DMULTISAMPLE_NONE;
	d3dParams.SwapEffect = D3DSWAPEFFECT_COPY;
	d3dParams.hDeviceWindow = window;
	d3dParams.Windowed = windowed;
	d3dParams.EnableAutoDepthStencil = FALSE;
	d3dParams.FullScreen_RefreshRateInHz = windowed ? 0 : refreshRate;
	d3dParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	CComPtr<IDirect3DDevice9> d3dDevice;
	if (d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, nullptr, D3DCREATE_MULTITHREADED | D3DCREATE_SOFTWARE_VERTEXPROCESSING, 
		&d3dParams, &d3dDevice) != S_OK)
		return false;

	m_d3d = d3d;
	m_d3dParams = d3dParams;
	m_d3dDevice = d3dDevice;
	return true;
}

IDirect3DDevice9* A2DDevice::GetD3DDevice( void ) const
{
	return m_d3dDevice;
}